package cn.ito.zjgsu.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import cn.ito.zjgsu.domain.View;
import cn.ito.zjgsu.domain.ViewExample;
import cn.ito.zjgsu.domain.wrapper.ViewWrapper;
import cn.ito.zjgsu.service.ViewService;
import cn.ito.zjgsu.utils.StatusCodeUtil;

@Controller
@RequestMapping("/admin/view")
public class ViewController {
	
	@Resource
	private ViewService viewService;
	
	@Autowired
	private StatusCodeUtil statusCodeUtil;
	
	private static Logger logger = Logger.getLogger(ItypePtypeController.class);

	@RequestMapping("/")
	public String index() {
		return "sys/viewMan";
	}
	
	//3保存状态
	@RequestMapping(value = "/columns/{modelName}" , method = RequestMethod.PUT)
	@ResponseBody
	public String saveState(@RequestParam("field") String[] fields,
			@PathVariable("modelName") String modelName){
		logger.info(fields);
		List<View> views = new ArrayList<View>();
		for(int i = 0 ;  i < fields.length ; i++){
			View view = new View();
			view.setChecked(true);
			view.setFieldname(fields[i]);
			view.setModelName(modelName);
			view.setNumber(i);
			views.add(view);
		}
		String status = viewService.saveState(views);
		return statusCodeUtil.toJsonStatus(status);
	}
	
	//2查询所有字段
	@RequestMapping(value = "/columns/{modelName}" , method = RequestMethod.GET)
	@ResponseBody
	public String queryAllField(@PathVariable String modelName){
		logger.info(modelName);
		ViewExample viewExample = new ViewExample();
		viewExample.or().andModelNameEqualTo(modelName);
		List<View> views = viewService.queryViewsByExample(viewExample);
		String json = ViewWrapper.toJsonArrayString(ViewWrapper.wrapList(views));
		return json;
		
	}
	
	//1查询所有模块名
	@RequestMapping(value = "/models" , method = RequestMethod.GET)
	@ResponseBody
	public String queryAllModels(){
		List<String> modelNames = viewService.queryAllModelName();
		JSONObject json = new JSONObject();
		json.put("modelNames", modelNames);
		return json.toJSONString();
	}
	
}
